package com.epam.my.Pages;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

import com.epam.my.Kulibaba.Email;
import com.epam.my.Kulibaba.SorterListOf;
import com.google.common.collect.Lists;

public class MailPage extends InternalPage {
	@FindBy(css = "button.uiButton.uiButtonNormal")
	public WebElement wrightButton;

	@FindBy(css = ".messagesListBody.ScrollBar div.ScrollBarWrap")
	public WebElement container;

	@FindBy(css = "button.uiButton.uiButtonAside.uiButtonFlat.buttonCheckMail")
	public WebElement buttonInboxLetter;
		
	@Override
	public boolean isOnThisPage() {
		return wrightButton.isDisplayed();
	}

	@Override
	public void tryToOpen() {
		MyPageFactory.getPage(driver, LoginPage.class)
				.loginWithValidCredentials("nadin_qwerty", "@rambler.ru", "qwerty");
	}

	public RightMailPage createNewEmail() {
		wrightButton.click();
		return MyPageFactory.getPage(driver, RightMailPage.class);
	}
	
	public MailPage checkInboxLetter() throws InterruptedException {
		Thread.sleep(10000);
		buttonInboxLetter.click();
		return MyPageFactory.getPage(driver, MailPage.class);
	}
	
	public SorterListOf<Email> getEmails() {
		List<Email> emails = Lists.newArrayList();
		List<WebElement> itemEmails = container.findElements
				(By.cssSelector("div[class^='listItem']"));		
		for (WebElement item : itemEmails) {
			emails.add(ConvertItemToEmails(item));
		}
		return new SorterListOf<Email>(emails);
	}

	private Email ConvertItemToEmails(WebElement item) {
		return new Email().
				withSenderName(item.findElement(By.cssSelector("a[class$='ColumnSender']")).getText()).				
				withSubjectEmail(item.findElement(By.cssSelector("a[class$='ColumnSubject']")).getText());
	}
}
